<?php

namespace App\Jobs;

use Exception;
use App\Models\Attendance;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\DB;
use App\Package\Attendance\Verdict;
use Illuminate\Support\Facades\Log;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\Statistical\MonthlyAttendanceReports;

/**
 * 考勤报表生成任务
 *
 * Date: 11/05/2018
 * @author George
 * @package App\Jobs
 */
class AttendanceReportGenerate implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	/**
	 * 定义存储属性
	 *
	 * @var Attendance
	 * Date: 11/05/2018
	 * @author George
	 */
    protected $attendance;

	/**
	 * AttendanceReportGenerate constructor.
	 * @param Attendance $attendance
	 */
    public function __construct(Attendance $attendance)
    {
    	$this->attendance = $attendance;
    }

	/**
	 * 处理考勤信息
	 *
	 * Date: 11/05/2018
	 * @author George
	 * @throws \Throwable
	 */
    public function handle()
    {
		try {
			// 获取考勤记录中的天
			$day = substr($this->attendance->checkin_time, 8, 2);
			$genre_code = $this->attendance->genre->code;

			// 判断一天的记录是否完成，如果完成则进行统计
			if ($this->attendance->checkout_time) {
				$year = substr($this->attendance->checkin_time, 0, 4);
				$month = substr($this->attendance->checkin_time, 5, 2);
				// 查询数据库是否存在报表记录
				$record = MonthlyAttendanceReports::query()
					->where('year', $year)
					->where('month', $month)
					->where('project_id', $this->attendance->project_id)
					->where('user_id', $this->attendance->user_id)->first();
				// 如果存在则更新统计信息，否则创建一条汇总记录
				if ($record) {
					// 根据考勤记录计算并生成对应的编码
					$record->{'day_' . $day} = Verdict::status($this->attendance->checkin_status, $this->attendance->checkout_status, $genre_code) ?: '';
					$record->saveOrFail();
				} else {
					// 获取用户和岗位信息
					$user = DB::table('users')
						->leftJoin('positions', 'users.position_id', '=', 'positions.id')
						->where('users.id', $this->attendance->user_id)
						->select(['users.name', 'positions.name as position'])->first();

					$attributes = [
						'company_id' => $this->attendance->company_id,
						'project_id' => $this->attendance->project_id,
						'project_name' => optional($this->attendance->project)->name,
						"day_{$day}" => Verdict::status($this->attendance->checkin_status, $this->attendance->checkout_status, $genre_code) ?: '',
						'year' => $year,
						'month' => $month,
						'user_id' => $this->attendance->user_id,
						'user_name' => optional($user)->name,
						'position' => optional($user)->position,
					];

					// 创建报表记录
					MonthlyAttendanceReports::create($attributes);
				}
			}
		} catch (Exception $exception) {
			Log::error($exception);
		}
	}
}
